<template>
  <div class="device-detail-container">
    <el-page-header @back="goBack" title="设备详情" />
    
    <div v-loading="loading">
      <el-row :gutter="20" class="top-row">
        <!-- 设备信息卡片 -->
        <el-col :xs="24" :sm="24" :md="15" :lg="15" :xl="15">
          <el-card shadow="never" class="detail-card">
            <template #header>
              <div class="card-header">
                <span>设备信息</span>
                <div>
                  <el-button type="primary" @click="editDevice" size="small">编辑</el-button>
                  <el-button 
                    :type="device.status === 0 ? 'success' : 'warning'" 
                    @click="toggleDeviceStatus" 
                    size="small"
                  >
                    {{ device.status === 0 ? '启用' : '禁用' }}
                  </el-button>
                  <el-button type="danger" @click="confirmDeleteDevice" size="small">删除</el-button>
                </div>
              </div>
            </template>
            
            <el-descriptions :column="2" border>
              <el-descriptions-item label="设备ID">{{ device.id }}</el-descriptions-item>
              <el-descriptions-item label="设备名称">{{ device.name }}</el-descriptions-item>
              <el-descriptions-item label="设备编号">{{ device.deviceCode }}</el-descriptions-item>
              <el-descriptions-item label="设备类型">{{ getDeviceTypeText(device.type) }}</el-descriptions-item>
              <el-descriptions-item label="设备位置">{{ device.location || '未设置' }}</el-descriptions-item>
              <el-descriptions-item label="设备状态">
                <el-tag :type="device.status === 1 ? 'success' : 'danger'">
                  {{ device.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">{{ formatDateTime(device.createdTime) }}</el-descriptions-item>
              <el-descriptions-item label="更新时间">{{ formatDateTime(device.updatedTime) }}</el-descriptions-item>
              <el-descriptions-item label="设备规格" :span="2">
                {{ device.specifications || '未设置' }}
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
        </el-col>
        
        <!-- 设备状态和收入卡片 -->
        <el-col :xs="24" :sm="24" :md="9" :lg="9" :xl="9">
          <!-- 设备状态卡片 -->
          <el-card shadow="never" class="status-card">
            <template #header>
              <div class="card-header">
                <span>设备状态</span>
                <el-tag :type="device.status === 1 ? 'success' : 'danger'">
                  {{ device.status === 1 ? '在线' : '离线' }}
                </el-tag>
              </div>
            </template>
            
            <div class="status-info">
              <div class="status-item">
                <div class="status-label">状态更新时间</div>
                <div class="status-value">{{ formatDateTime(device.updatedTime) }}</div>
              </div>
              <div class="status-item">
                <div class="status-label">最近活动时间</div>
                <div class="status-value">{{ formatDateTime(device.updatedTime) }}</div>
              </div>
              <div class="status-item">
                <div class="status-label">当前广告</div>
                <div class="status-value">{{ currentAd ? currentAd.title : '无正在投放广告' }}</div>
              </div>
              <div class="status-item">
                <div class="status-label">历史广告数</div>
                <div class="status-value">{{ adCount }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 设备地图位置卡片 -->
      <el-row :gutter="20" class="map-row">
        <el-col :span="24">
          <el-card shadow="never" class="map-card">
            <template #header>
              <div class="card-header">
                <span>设备位置</span>
                <div>
                  <el-button 
                    type="primary" 
                    size="small"
                    @click="refreshLocation"
                    :loading="mapLoading"
                  >
                    <el-icon><Refresh /></el-icon>
                    刷新位置
                  </el-button>
                </div>
              </div>
            </template>
            
            <div class="map-container">
              <div v-if="hasLocation" id="device-map" class="map-content"></div>
              <el-empty v-else description="暂无位置信息" />
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 收入统计和设备统计 -->
      <el-row :gutter="20" class="middle-row">
        <!-- 收入统计卡片 -->
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-card shadow="never" class="income-card">
            <template #header>
              <div class="card-header">
                <span>收入统计</span>
              </div>
            </template>
            
            <div class="income-info" v-loading="incomeLoading">
              <el-row :gutter="20">
                <el-col :span="12">
                  <div class="income-item">
                    <div class="income-label">本月收入</div>
                    <div class="income-value positive">¥{{ incomeStats.monthly.toFixed(2) }}</div>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="income-item">
                    <div class="income-label">累计收入</div>
                    <div class="income-value positive">¥{{ incomeStats.total.toFixed(2) }}</div>
                  </div>
                </el-col>
              </el-row>
              <div class="income-divider"></div>
              <div class="income-chart-title">最近7天收入趋势</div>
              <div class="income-chart" ref="incomeChartRef"></div>
            </div>
          </el-card>
        </el-col>
        
        <!-- 统计数据卡片 -->
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-card shadow="never" class="statistics-card">
            <template #header>
              <div class="card-header">
                <span>统计数据</span>
                <el-button type="primary" size="small" @click="exportStatistics" :loading="exportLoading">
                  <el-icon><Download /></el-icon> 导出数据
                </el-button>
              </div>
            </template>
            
            <div class="statistics-info" v-loading="statisticsLoading">
              <el-row :gutter="20">
                <el-col :span="12">
                  <div class="stat-card">
                    <div class="stat-title">总播放次数</div>
                    <div class="stat-value">{{ statistics.totalPlayCount || 0 }}</div>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="stat-card">
                    <div class="stat-title">总观看次数</div>
                    <div class="stat-value">{{ statistics.totalViewCount || 0 }}</div>
                  </div>
                </el-col>
              </el-row>
              
              <div class="statistics-chart-title">最近7天播放/观看趋势</div>
              <div class="statistics-chart" ref="statisticsChartRef"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      
      <!-- 广告排期和广告统计标签页 -->
      <el-row :gutter="20" class="bottom-row">
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <el-tabs v-model="activeTab" class="detail-tabs">
            <el-tab-pane label="广告排期" name="adSchedules">
              <div class="tab-content">
                <div class="ad-schedules-container" v-loading="schedulesLoading">
                  <el-table :data="adSchedules" style="width: 100%" border v-if="adSchedules.length > 0">
                    <el-table-column prop="id" label="ID" width="80" />
                    <el-table-column prop="title" label="广告标题" min-width="150" />
                    <el-table-column prop="start_time" label="开始时间" width="180">
                      <template #default="scope">
                        {{ formatDateTime(scope.row.start_time) }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="end_time" label="结束时间" width="180">
                      <template #default="scope">
                        {{ formatDateTime(scope.row.end_time) }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="revenue" label="收入" width="120">
                      <template #default="scope">
                        ¥{{ Number(scope.row.revenue).toFixed(2) }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="status" label="状态" width="120">
                      <template #default="scope">
                        <el-tag :type="getAdStatusType(scope.row.status)">
                          {{ getAdStatusText(scope.row.status) }}
                        </el-tag>
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-empty description="暂无广告排期数据" v-else />
                  
                  <div class="pagination-container" v-if="adSchedules.length > 0">
                    <el-pagination
                      v-model:current-page="schedulePagination.current"
                      v-model:page-size="schedulePagination.pageSize"
                      :page-sizes="[5, 10, 20, 50]"
                      layout="total, sizes, prev, pager, next, jumper"
                      :total="schedulePagination.total"
                      @size-change="handleScheduleSizeChange"
                      @current-change="handleScheduleCurrentChange"
                    />
                  </div>
                </div>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="广告统计" name="adStatistics">
              <div class="tab-content">
                <div class="ad-statistics-container" v-loading="adStatsLoading">
                  <el-table :data="adStats" style="width: 100%" border v-if="adStats.length > 0">
                    <el-table-column prop="ad_id" label="广告ID" width="80" />
                    <el-table-column prop="ad_title" label="广告标题" min-width="150" />
                    <el-table-column prop="advertiser_name" label="广告主" width="120" />
                    <el-table-column prop="play_count" label="播放次数" width="120" />
                    <el-table-column prop="view_count" label="观看次数" width="120" />
                    <el-table-column label="观看率" width="120">
                      <template #default="scope">
                        {{ calculateViewRate(scope.row.play_count, scope.row.view_count) }}%
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-empty description="暂无广告统计数据" v-else />
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed, watch, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import * as echarts from 'echarts';
import { Download, Refresh } from '@element-plus/icons-vue';
// 正确导入方式
import AMapLoader from '@amap/amap-jsapi-loader'
import { 
  getDeviceDetail, 
  enableDevice, 
  disableDevice, 
  deleteDevice,
  getDeviceStatistics,
  getDeviceIncomeStats,
  getDeviceWeeklyIncome,
  getDeviceAdSchedules,
  exportDeviceStatistics
} from '@/api/device';

const route = useRoute();
const router = useRouter();
const deviceId = route.params.id;

// 页面状态
const loading = ref(false);
const incomeLoading = ref(false);
const statisticsLoading = ref(false);
const schedulesLoading = ref(false);
const adStatsLoading = ref(false);
const activeTab = ref('adSchedules');
const incomeChartRef = ref(null);
const statisticsChartRef = ref(null);
let incomeChart = null;
let statisticsChart = null;
// 新增地图相关
const mapLoading = ref(false);
let mapInstance = null;
let marker = null;

// 导出相关状态
const exportLoading = ref(false);

// 设备详情数据
const device = reactive({
  id: '',
  name: '',
  deviceCode: '',
  ownerId: '',
  location: '',
  type: '',
  status: 0,
  specifications: '',
  createdTime: '',
  updatedTime: '',
  latitude: null,
  longitude: null
});

// 计算是否有位置信息
const hasLocation = computed(() => {
  console.log('hasLocation', device.latitude, device.longitude);
  return device.latitude && device.longitude;
});

// 当前正在投放的广告
const currentAd = ref(null);
// 广告历史总数
const adCount = ref(0);

// 收入统计
const incomeStats = reactive({
  monthly: 0,
  total: 0,
  weeklyData: []
});

// 设备统计数据
const statistics = reactive({
  totalPlayCount: 0,
  totalViewCount: 0,
  dailyStats: [],
  weeklyStats: []
});

// 广告排期数据
const adSchedules = ref([]);
const schedulePagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
});

// 广告统计数据
const adStats = ref([]);

// 返回上一页
const goBack = () => {
  router.back();
};

// 获取设备详情
const fetchDeviceDetail = async () => {
  loading.value = true;
  try {
    const { data } = await getDeviceDetail(deviceId);
    console.log('deviceDetail', data);
    if (data.code === 200) {
      Object.assign(device, data.data);
      await fetchDeviceData();
    } else {
      ElMessage.error(data.message || '获取设备详情失败');
      goBack();
    }
  } catch (error) {
    console.error('获取设备详情失败:', error);
    ElMessage.error('获取设备详情失败');
    goBack();
  } finally {
    loading.value = false;
  }
};

// 获取设备相关数据
const fetchDeviceData = async () => {
  await Promise.all([
    fetchIncomeStats(),
    fetchDeviceStatistics(),
    fetchAdSchedules(),
  ]);
};

// 获取收入统计
const fetchIncomeStats = async () => {
  incomeLoading.value = true;
  try {
    // 获取收入统计
    const { data: statsData } = await getDeviceIncomeStats(deviceId);
    if (statsData.code === 200) {
      incomeStats.monthly = Number(statsData.data.monthly) || 0;
      incomeStats.total = Number(statsData.data.total) || 0;
    }
    
    // 获取每周收入
    const { data: weeklyData } = await getDeviceWeeklyIncome(deviceId);
    if (weeklyData.code === 200) {
      incomeStats.weeklyData = weeklyData.data;
      renderIncomeChart();
    }
  } catch (error) {
    console.error('获取收入统计失败:', error);
  } finally {
    incomeLoading.value = false;
  }
};

// 获取设备统计数据
const fetchDeviceStatistics = async () => {
  statisticsLoading.value = true;
  try {
    const { data } = await getDeviceStatistics(deviceId);
    console.log('设备统计数据:', data);
    if (data.code === 200) {
      statistics.totalPlayCount = data.data.totalPlayCount || 0;
      statistics.totalViewCount = data.data.totalViewCount || 0;
      statistics.dailyStats = data.data.dailyStats || [];
      statistics.weeklyStats = data.data.weeklyStats || [];
      adStats.value = data.data.adStats || [];
      
      // 设置广告数量
      adCount.value = adStats.value.length;
      
      // 假设第一个活跃广告就是当前广告
      const activeAd = adStats.value.find(ad => ad.play_count > 0);
      if (activeAd) {
        currentAd.value = {
          id: activeAd.ad_id,
          title: activeAd.ad_title
        };
      }
      
      renderStatisticsChart();
    }
  } catch (error) {
    console.error('获取设备统计数据失败:', error);
  } finally {
    statisticsLoading.value = false;
    adStatsLoading.value = false;
  }
};

// 获取广告排期
const fetchAdSchedules = async () => {
  schedulesLoading.value = true;
  try {
    const params = {
      pageNum: schedulePagination.current,
      pageSize: schedulePagination.pageSize
    };
    
    const { data } = await getDeviceAdSchedules(deviceId, params);
    if (data.code === 200) {
      adSchedules.value = data.data.records;
      schedulePagination.total = data.data.total;
    }
  } catch (error) {
    console.error('获取广告排期失败:', error);
  } finally {
    schedulesLoading.value = false;
  }
};

// 编辑设备
const editDevice = () => {
  router.push(`/device-owner/devices/edit/${deviceId}`);
};

// 切换设备状态
const toggleDeviceStatus = async () => {
  try {
    let response;
    if (device.status === 0) {
      response = await enableDevice(deviceId);
    } else {
      response = await disableDevice(deviceId);
    }
    
    const { data } = response;
    
    if (data.code === 200) {
      ElMessage.success(device.status === 0 ? '设备已启用' : '设备已禁用');
      // 更新本地设备状态
      device.status = device.status === 0 ? 1 : 0;
    } else {
      ElMessage.error(data.message || '操作失败');
    }
  } catch (error) {
    console.error('切换设备状态失败:', error);
    ElMessage.error('操作失败');
  }
};

// 确认删除设备
const confirmDeleteDevice = () => {
  ElMessageBox.confirm('确定要删除该设备吗？此操作不可恢复。', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    performDeleteDevice();
  }).catch(() => {});
};

// 执行删除设备
const performDeleteDevice = async () => {
  try {
    const { data } = await deleteDevice(deviceId);
    
    if (data.code === 200) {
      ElMessage.success('删除设备成功');
      router.push('/device-owner/devices');
    } else {
      ElMessage.error(data.message || '删除设备失败');
    }
  } catch (error) {
    console.error('删除设备失败:', error);
    ElMessage.error('删除设备失败');
  }
};

// 导出设备统计数据
const exportStatistics = async () => {
  exportLoading.value = true;
  try {
    const response = await exportDeviceStatistics(deviceId);
    
    // 创建Blob对象
    const blob = new Blob([response.data], { 
      type: 'application/vnd.ms-excel' 
    });
    
    // 创建下载链接
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    
    // 生成文件名
    const deviceName = device.name || 'device';
    const date = new Date().toISOString().split('T')[0];
    link.download = `设备统计数据_${deviceName}_${date}.xlsx`;
    
    // 触发下载
    document.body.appendChild(link);
    link.click();
    
    // 清理
    URL.revokeObjectURL(link.href);
    document.body.removeChild(link);
    
    ElMessage.success('导出成功');
  } catch (error) {
    console.error('导出设备统计数据失败:', error);
    ElMessage.error('导出设备统计数据失败');
  } finally {
    exportLoading.value = false;
  }
};

// 渲染收入图表
const renderIncomeChart = () => {
  if (!incomeChartRef.value) return;
  
  // 准备数据
  const dateLabels = incomeStats.weeklyData.map(item => {
    const date = new Date(item.date);
    return `${date.getMonth() + 1}/${date.getDate()}`;
  });
  
  const incomeData = incomeStats.weeklyData.map(item => Number(item.amount));
  
  // 销毁旧的图表实例
  if (incomeChart) {
    incomeChart.dispose();
  }
  
  // 创建新的图表实例
  incomeChart = echarts.init(incomeChartRef.value);
  
  // 设置图表选项
  const option = {
    grid: {
      top: 10,
      right: 10,
      bottom: 20,
      left: 40
    },
    xAxis: {
      type: 'category',
      data: dateLabels,
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      },
      axisLabel: {
        fontSize: 10
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      axisLabel: {
        fontSize: 10
      },
      splitLine: {
        lineStyle: {
          color: '#eee'
        }
      }
    },
    series: [
      {
        name: '日收入',
        type: 'bar',
        data: incomeData,
        itemStyle: {
          color: '#67C23A'
        },
        barWidth: '60%'
      }
    ],
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br />收入: ¥{c}'
    }
  };
  
  // 渲染图表
  incomeChart.setOption(option);
};

// 渲染统计图表
const renderStatisticsChart = () => {
  if (!statisticsChartRef.value) return;
  
  // 准备数据
  const dateLabels = statistics.weeklyStats.map(item => {
    const date = new Date(item.date);
    return `${date.getMonth() + 1}/${date.getDate()}`;
  });
  
  const playData = statistics.weeklyStats.map(item => Number(item.play_count));
  const viewData = statistics.weeklyStats.map(item => Number(item.view_count));
  
  // 销毁旧的图表实例
  if (statisticsChart) {
    statisticsChart.dispose();
  }
  
  // 创建新的图表实例
  statisticsChart = echarts.init(statisticsChartRef.value);
  
  // 设置图表选项
  const option = {
    grid: {
      top: 30,
      right: 20,
      bottom: 20,
      left: 40
    },
    legend: {
      data: ['播放次数', '观看次数'],
      top: 0
    },
    xAxis: {
      type: 'category',
      data: dateLabels,
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: '#eee'
        }
      }
    },
    series: [
      {
        name: '播放次数',
        type: 'line',
        data: playData,
        itemStyle: {
          color: '#409EFF'
        },
        smooth: true
      },
      {
        name: '观看次数',
        type: 'line',
        data: viewData,
        itemStyle: {
          color: '#FF9900'
        },
        smooth: true
      }
    ],
    tooltip: {
      trigger: 'axis'
    }
  };
  
  // 渲染图表
  statisticsChart.setOption(option);
};

// 新增方法：初始化地图
const initMap = async () => {
  console.info(hasLocation.value);
  if (!hasLocation.value) return;
  
  try {
    const AMap = await AMapLoader.load({
      key: '2bd1031aa08256eeba5539a5577c3ff7', // 请替换为您的高德地图API密钥
      version: '2.0',
      plugins: ['AMap.Marker']
    });

    if (mapInstance) {
      mapInstance.destroy();
    }

    console.info('地图初始化成功');
    console.info(device.longitude, device.latitude);
    mapInstance = new AMap.Map('device-map', {
      zoom: 15,
      center: [device.longitude, device.latitude]
    });

    marker = new AMap.Marker({
      position: new AMap.LngLat(device.longitude, device.latitude),
      title: device.name,
      content: `<div class="custom-marker">
                  <div class="marker-inner"></div>
                </div>`
    });
    
    mapInstance.add(marker);

    // 创建标签
    const infoWindow = new AMap.InfoWindow({
      content: `<div class="device-info-window">
                  <h4>${device.name}</h4>
                  <p>设备编号: ${device.deviceCode}</p>
                  <p>位置: ${device.location}</p>
                </div>`,
      offset: new AMap.Pixel(0, -30)
    });

    // 绑定事件
    marker.on('click', () => {
      infoWindow.open(mapInstance, marker.getPosition());
    });

  } catch (error) {
    console.error('地图初始化失败:', error);
    ElMessage.error('地图加载失败，请检查API密钥或网络连接');
  }
};

// 刷新位置
const refreshLocation = async () => {
  mapLoading.value = true;
  try {
    await fetchDeviceDetail();
    await nextTick();
    await initMap();
  } catch (error) {
    console.error('刷新位置失败:', error);
    ElMessage.error('刷新位置失败');
  } finally {
    mapLoading.value = false;
  }
};

// 处理广告排期分页
const handleScheduleSizeChange = (size) => {
  schedulePagination.pageSize = size;
  fetchAdSchedules();
};

const handleScheduleCurrentChange = (page) => {
  schedulePagination.current = page;
  fetchAdSchedules();
};

// 计算观看率
const calculateViewRate = (playCount, viewCount) => {
  if (!playCount || playCount === 0) return 0;
  const rate = (viewCount / playCount) * 100;
  return rate.toFixed(2);
};

// 获取广告状态颜色
const getAdStatusType = (status) => {
  switch (status) {
    case 'RUNNING':
      return 'success';
    case 'PENDING':
      return 'warning';
    case 'COMPLETED':
      return 'info';
    case 'CANCELLED':
      return 'danger';
    default:
      return 'info';
  }
};

// 获取广告状态文本
const getAdStatusText = (status) => {
  switch (status) {
    case 'RUNNING':
      return '执行中';
    case 'PENDING':
      return '待执行';
    case 'COMPLETED':
      return '已完成';
    case 'CANCELLED':
      return '已取消';
    default:
      return '未知';
  }
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '未知';
  const date = new Date(dateTime);
  return date.toLocaleString();
};

// 获取设备类型文本
const getDeviceTypeText = (type) => {
  const typeMap = {
    'LCD_SCREEN': 'LCD屏幕',
    'LED_DISPLAY': 'LED显示屏',
    'DIGITAL_SIGNAGE': '数字标牌',
    'TOUCH_SCREEN': '触摸屏',
    'INTERACTIVE_KIOSK': '信息亭',
    'OTHER': '其他'
  };
  return typeMap[type] || '未知';
};

// 窗口大小变化时重新渲染图表
const handleResize = () => {
  if (incomeChart) {
    incomeChart.resize();
  }
  if (statisticsChart) {
    statisticsChart.resize();
  }
  if (mapInstance) {
    mapInstance.setFitView();
  }
};

// 当设备数据更新时初始化地图
watch(
  () => [device.latitude, device.longitude],
  () => {
    if (hasLocation.value) {
      nextTick(() => {
        initMap();
      });
    }
  }
);

onMounted(() => {
  fetchDeviceDetail().then(() => {
    // 确保数据加载完成后再初始化地图
    nextTick(() => {
      console.log('页面渲染完成，初始化地图');
      initMap();
    });
  });
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  
  // 清理图表实例
  if (incomeChart) {
    incomeChart.dispose();
    incomeChart = null;
  }
  if (statisticsChart) {
    statisticsChart.dispose();
    statisticsChart = null;
  }
  
  // 清理地图实例
  if (mapInstance) {
    mapInstance.destroy();
    mapInstance = null;
  }
});
</script>

<style scoped>
.device-detail-container {
  padding: 20px;
}

.top-row, .middle-row, .bottom-row, .map-row {
  margin-top: 20px;
  margin-bottom: 20px;
}

.detail-card {
  height: 100%;
  margin-bottom: 20px;
}

.status-card {
  margin-bottom: 20px;
  min-height: 250px;
}

.income-card, .statistics-card {
  margin-bottom: 20px;
  min-height: 350px;
}

.map-card {
  min-height: 400px;
}

.map-container {
  position: relative;
  height: 100%;
}

.map-content {
  height: 350px;
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
}

.custom-marker {
  position: relative;
  width: 25px;
  height: 35px;
  background-color: #409EFF;
  border-radius: 50% 50% 50% 0;
  transform: rotate(-45deg);
  box-shadow: 0 2px 6px rgba(0,0,0,0.3);
}

.marker-inner {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) rotate(45deg);
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background-color: white;
}

.device-info-window {
  padding: 8px;
  max-width: 250px;
}

.device-info-window h4 {
  margin: 0 0 5px 0;
  color: #303133;
}

.device-info-window p {
  margin: 5px 0;
  color: #606266;
  font-size: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-info {
  padding: 10px 0;
}

.status-item {
  margin-bottom: 15px;
  display: flex;
  flex-direction: column;
}

.status-label {
  color: #909399;
  font-size: 14px;
  margin-bottom: 5px;
}

.status-value {
  font-size: 14px;
  font-weight: bold;
}

.income-info {
  padding: 10px 0;
}

.income-item {
  padding: 10px;
  text-align: center;
  margin-bottom: 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.income-label {
  color: #909399;
  font-size: 14px;
  margin-bottom: 5px;
}

.income-value {
  font-size: 18px;
  font-weight: bold;
}

.income-value.positive {
  color: #67C23A;
}

.income-divider {
  height: 1px;
  background-color: #EBEEF5;
  margin: 10px 0;
}

.income-chart-title, .statistics-chart-title {
  font-size: 14px;
  color: #303133;
  margin-bottom: 10px;
  text-align: center;
}

.income-chart, .statistics-chart {
  height: 180px;
  width: 100%;
}

.statistics-info {
  padding: 10px 0;
}

.stat-card {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 15px;
  text-align: center;
  margin-bottom: 20px;
}

.stat-title {
  color: #909399;
  font-size: 14px;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.detail-tabs {
  margin-top: 20px;
}

.tab-content {
  padding: 20px 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .top-row > .el-col, 
  .middle-row > .el-col,
  .bottom-row > .el-col {
    margin-bottom: 20px;
  }
  
  .income-chart, .statistics-chart {
    height: 150px;
  }
  
  .map-content {
    height: 250px;
  }
  
  .income-card, .status-card, .statistics-card, .map-card {
    min-height: auto;
  }
}
</style>